package com.hyy.backend.controller;

import com.hyy.backend.entity.UserInfo;
import com.hyy.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> credentials) {
        String userName = credentials.get("userName");
        String password = credentials.get("password");
        UserInfo user = userService.login(userName, password);
        if (user != null) {
            return ResponseEntity.ok(user); // 或返回 token 等
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserInfo userInfo) {
        if (userService.selectByUserName(userInfo.getUserName()) != null) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
        userService.insertUser(userInfo);
        return ResponseEntity.ok("注册成功");
    }

    // ✅ 新增：修改用户信息
    @PostMapping("/updateProfile")
    public ResponseEntity<?> updateUser(@RequestBody UserInfo userInfo) {
        boolean success = userService.updateUserInfo(userInfo);
        if (success) {
            return ResponseEntity.ok("用户信息更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("更新失败");
        }
    }

    @PostMapping("/updatePassword")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, String> data) {
        int userId = Integer.parseInt(data.get("userId"));
        String oldPassword = data.get("oldPassword");
        String newPassword = data.get("newPassword");

        boolean result = userService.updatePassword(userId, oldPassword, newPassword);
        if (result) {
            return ResponseEntity.ok("密码修改成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("旧密码错误");
        }
    }
}
